import common from '@/api/common.js'
import {
	reactive,
	inject,
	ref,
	watch,
	getCurrentInstance
} from 'vue'
import {
	useStore
} from 'vuex'
import {
	onLoad,
	onShow,
	onUnload,
	onReady
} from '@dcloudio/uni-app'
import palyer from './components/palyer.vue'
import $event from './index.js'
const store = useStore()
const socket: any = inject("$socket");
let voiceTimer: any = ref(0)
let voiceShow = ref(false)
let timer = null
let clientY = reactive({
	moveY: 0,
	startY: 0
})
interface obj {
	[propName: string]: any;
}
//#ifdef APP-PLUS
const recorderManager: any = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
// #endif
let gather: any = reactive({
	inputStyle: {
		"background": "#fff",
		"border-radius": "40rpx"
	},
	sendMsg: '',
	scrollTop: 0,
	scrollToView: '',
	isLoading: false,
	scrollAnimation: false,
	messageList: [],
	imgArr: [],
	emoji: {
		list: [],
		emojiPage: 1,
		emojiTotal: 0,
		swiperSize: 1,
		swiperCurrent: 0
	},
	userinfo: {}, //接收者
	selfInfo: uni.getStorageSync('userinfo'), //自己的
	palyer: false, //音视频弹窗
	palyerType: 0,
})
/* 视频通话相关 */
let myVideo = ref(null)
let isAccept = ref(false) //是否接受通话
let v1 = ref() //自己
let v2 = ref() //他人
let all: any = reactive({
	config: {
		'muted': false, //是否静音
		'beauty': 0, //美艳0-9
		'whiteness': 0, //美白0-9
		'background-mute': true, //进入后台是否静音
		'enable-mic': true, //开启关闭麦克风
		'audio-volume-type': 'voicecall', //媒体音量
		'enable-camera': true, //是否开启摄像头
	},
	pusherCalss: {
		width: '100%',
		height: '1200rpx'
	},

	// form本人测试请求的参数，不发请求可以不加
	form: {
		liveroomTitle: null, // 标题
		equipmentType: 1 // 设备类型（1.手机 2.电脑）
	},
	startState: false, // 直播状态（false 关闭）
	context: null
})
/* end */
//动态padding
let emojiPop = ref(false)
let voicePop = ref(false)

let paddingBottom = ref(180)
let menuPad = ref(170)
let current: any = ref(0) //预览当前页
//获取表情包
const getEmo = async (page: number, pageSize: number) => {
	const res = await common.emoji(page, pageSize)
	gather.emoji.list = res.data
	gather.emoji.emojiTotal = res.total
	gather.emoji.swiperSize = res.swiperSize
}
//滚动到顶部/左边
const loadHistory = () => {

}
//点击抽屉
const onPop = (type: number) => {
	//初始化
	paddingBottom.value = 180
	menuPad.value = 170
	if (type === 1) {
		voicePop.value = !voicePop.value
		emojiPop.value = false
	} else if (type === 4) {
		emojiPop.value = !emojiPop.value
		voicePop.value = false
	} else {
		emojiPop.value = false
		voicePop.value = false
	}
}
//预览
const preview = (img: String) => {
	for (let i in gather.imgArr) {
		if (gather.imgArr[i] === img) {
			current.value = i
		}
	}
	uni.previewImage({
		urls: gather.imgArr,
		current: Number(current.value),
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function(data) {
				console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
			},
			fail: function(err) {
				console.log(err.errMsg);
			}
		}
	});
}

const onEmoji = (item: String) => {
	gather.sendMsg = gather.sendMsg.concat(item)
}
const listSwitch = (e: obj) => {
	if (!e.detail.current) return
	getEmo(e.detail.current, 80)
}

watch([emojiPop, voicePop], (newValue) => {
	if (newValue[0] || newValue[1]) {
		paddingBottom.value += 500
		menuPad.value += 500
	} else {
		paddingBottom.value = 180
		menuPad.value = 170
	}
})

//录音
const touchstart = (e: obj) => {
	clientY.startY = e.changedTouches[0].clientY
	clientY.moveY = e.changedTouches[0].clientY
	voiceShow.value = true
	recorderManager.start()
	timer = setInterval(() => {
		voiceTimer.value++
		if (voiceTimer.value > 10) {
			touchend()
		}
	}, 1000)
}
const touchend = () => {
	voiceShow.value = false
	recorderManager.stop();
	clearInterval(timer)
	if ((clientY.startY - clientY.moveY) > 300) {
		return uni.showToast({
			title: '取消成功',
			icon: 'none',
			success: () => {
				voiceTimer.value = 0
				clientY.moveY = 0
			}
		})
	}

	if (voiceTimer.value < 2) {
		return uni.showToast({
			title: '按键时间太短',
			icon: 'none',
			success: () => {
				voiceTimer.value = 0
				clientY.moveY = 0
			}
		})
	}
	recorderManager.onStop(function(res: obj) {
		uni.uploadFile({
			// @ts-ignore
			url: `${uni.$baseUrl}/uploadTwo`,
			name: 'file',
			filePath: res.tempFilePath,
			header: {
				"Authorization": uni.getStorageSync('token')
			},
			success: (res) => {
				let date = JSON.parse(res.data).data
				sendConent({
					payload: {
						src: date.url,
						time: voiceTimer.value
					}
				}, 2)
			}
		})

	});
}
const touchmove = (e: obj) => {
	clientY.moveY = e.changedTouches[0].clientY
}
const broadcast = (payload: string) => {
	// @ts-ignore
	innerAudioContext.src = `${uni.$baseUrl}/` + payload
	innerAudioContext.play()
}
//定位
const getAddress = () => {
	// #ifdef APP-PLUS
	uni.chooseLocation({
		success: (res) => {
			console.log(res)
		}
	})
	// #endif
}

const goPage = (type: boolean, str = '') => {
	if (!type) return uni.navigateBack()
	uni.navigateTo({
		url: str
	})
}
onShow(() => {
	socket.emit(`getMsg`, {
		receiveid: store.state.chatUser.userid,
		userid: gather.selfInfo.userid, //自己
	})
})
onUnload(() => {
	socket.removeListener('getMsg')
})
onReady(() => {
	all.context = uni.createLivePusherContext('livePusher', getCurrentInstance().proxy);
})
onLoad(() => {
	all.pusherCalss.height = uni.getSystemInfoSync().screenHeight
	gather.userinfo = store.state.chatUser
	getEmo(gather.emoji.swiperCurrent, 80)
	socket.on(`getMsg`, (msgList: IArguments) => {

		gather.messageList = [...gather.messageList, ...msgList]
		setTimeout(() => {
			gather.scrollToView = 'ID' + (gather.messageList.length - 1)
		}, 100)
	})
	socket.on('receive', (data: any) => {
		if (data.type !== 3) {
			gather.messageList = [...gather.messageList, data]
			setTimeout(() => {
				gather.scrollToView = 'ID' + (gather.messageList.length - 1)
			}, 100)
		} else {
			gather.palyer = true
			gather.palyerType = 1 //1接收 2发送
		}

	})
	//挂断
	socket.on('onRefuse', (data: object) => {
		gather.palyer = false
		console.log(data, '挂断')
		gather.messageList = [...gather.messageList, data]
	})
	//同意通话
	socket.on('onAccept', (data: object) => {
		gather.messageList = [...gather.messageList, data]
		//开启本地摄像头
		turnCamera()
	})
})
//开启本地摄像头
let turnCamera = () => {
	// #ifdef APP-PLUS
	all.context.startPreview()
	// #endif
	// #ifdef H5
	navigator.mediaDevices.getUserMedia({
			audio: true,
			video: true
		})
		.then((res) => {
			myVideo.value = res
			v1.value.srcObject = res
		})
		.catch((err) => {})
	// #endif

}
//发送
const send = () => {
	if (!gather.sendMsg) return
	sendConent({
		content: gather.sendMsg,
	}, 0)
}
//发送事件
const sendConent = (obj: obj, type: number = 0) => {
	let info = {
		...obj,
		type: type, //0文字 1图片 2音频 3视频
		userid: gather.selfInfo.userid, //自己
		username: gather.selfInfo.username,
		receiveid: gather.userinfo.userid, //
		receiveName: gather.userinfo.username, //别人
		id: store.state.chatID,
	}
	gather.messageList = [...gather.messageList, info]
	socket.emit('send_msg', info)
	gather.scrollAnimation = true
	voicePop.value = false
	gather.sendMsg = ''
	setTimeout(() => {
		gather.scrollToView = 'ID' + (gather.messageList.length - 1)
	}, 500)
}

const filterTimer = (time: number) => {
	if (time <= 5) return '10%'
	if (time > 5 && time <= 10) return '15%'
	if (time > 10 && time <= 20) return '20%'
	if (time > 20 && time <= 30) return '25%'
	return '30%'
}

//视频通话
const rtvVideo = () => {
	let info = {
		type: 3, //0文字 1图片 2音频 3视频
		userid: gather.selfInfo.userid, //自己
		username: gather.selfInfo.username,
		receiveid: gather.userinfo.userid, //
		receiveName: gather.userinfo.username, //别人
	}
	socket.emit('send_msg', info)
	gather.palyer = true
	gather.palyerType = 2 //1接收 2发送
}
// 接受
const onAccept = () => {
	let info = {
		content: '已接受',
		boo: true
	}
	onPalyer(info, (data: object) => {
		socket.emit('onAccept', data)
		isAccept.value = true
		// gather.palyer = false
	})
}
// 拒绝
const onRefuse = () => {
	let info = {
		content: '已拒绝',
		boo: false
	}
	onPalyer(info, (data: object) => {
		socket.emit('onRefuse', data)
		gather.palyer = false
	})


}
const onPalyer = (obj: object, cb: Function) => {
	let info = {
		...obj,
		type: 3, //0文字 1图片 2音频 3视频
		userid: gather.selfInfo.userid, //自己
		receiveid: gather.userinfo.userid, //
		palyerType: gather.palyerType,
	}
	cb(info)
}
const close = () => {
	gather.palyer = false
}
//网络状态通知事件
const netstatus = (detail: any) => {
	console.log(detail)
}
const error = (e: any) => {
	console.log('error:' + JSON.stringify(e))
}
// 状态发生变化
const statechange = (detail: any) => {

}